package cn.zdq.picture_lib.activity

import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import cn.zdq.picture_lib.R
import cn.zdq.picture_lib.adapter.PictureImageGridAdapter
import cn.zdq.picture_lib.config.PictureConfig
import cn.zdq.picture_lib.config.PictureSelectionConfig
import cn.zdq.picture_lib.listener.OnAlbumItemClickListener
import cn.zdq.picture_lib.listener.OnPhotoSelectChangedListener
import cn.zdq.picture_lib.listener.OnQueryDataResultListener
import cn.zdq.picture_lib.loader.LocalMediaLoader
import cn.zdq.picture_lib.model.LocalMedia
import cn.zdq.picture_lib.model.LocalMediaFolder
import cn.zdq.picture_lib.myselfview.PreloadRecyclerView
import cn.zdq.picture_lib.myselfview.window.FolderPopWindow
import cn.zdq.picture_lib.utils.ValueOf
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*
import kotlin.collections.ArrayList

/**
 * @Package: com.luck.pictureselector.test
 * @ClassName: TestPictureSelectorActivity
 * @Description:
 * @Author: zhoudequn
 * @CreateDate: 2021/8/11 09:50
 */
class PictureSelectorActivity : AppCompatActivity(), OnAlbumItemClickListener,
    View.OnClickListener {


    private lateinit var mRecyclerView: PreloadRecyclerView
    private lateinit var mTvPictureTitle: TextView
    private lateinit var mTvPictureRight: TextView
    private lateinit var mTvPictureOk: TextView
    private lateinit var mTvPicturePreview: TextView

    private lateinit var mIvArrow: ImageView
    private lateinit var mTitleBar: View

    private lateinit var mData: ArrayList<LocalMedia>
    private lateinit var mAdapter: PictureImageGridAdapter
    private var mPage: Int = 0
    private lateinit var folderWindow: FolderPopWindow
    private var hasMore: Boolean = true
    private lateinit var config: PictureSelectionConfig

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.picture_selector)
        mRecyclerView = findViewById(R.id.picture_recycler)
        mTvPictureTitle = findViewById(R.id.picture_title)
        mTvPictureRight = findViewById(R.id.picture_right)
        mTvPictureOk = findViewById(R.id.picture_tv_ok)
        mTvPicturePreview = findViewById(R.id.picture_id_preview)
        mIvArrow = findViewById(R.id.ivArrow)
        mTitleBar = findViewById(R.id.titleBar)

        mTvPictureOk.setOnClickListener(this)
        mTvPictureTitle.setOnClickListener(this)
        mTitleBar.setOnClickListener(this)
        initData2()
        initAfter()
    }

    private fun initData2() {
        config = PictureSelectionConfig.getInstance()
        lifecycleScope.launch(Dispatchers.IO) {
            LocalMediaLoader.instance
                .loadAllMedia2 { data: List<LocalMediaFolder>, currentPage: Int, isHasMore: Boolean ->
                    if (!isFinishing) {
                        initPageModel2(data)
                    }
                }
        }
    }

    private fun initAfter() {
        mTvPictureTitle.setTag(R.id.view_tag, -1)
        val gridLayout = GridLayoutManager(this, 4)
        mRecyclerView.layoutManager = gridLayout
        mData = ArrayList()
        mAdapter = PictureImageGridAdapter(this, mData, config)
        mRecyclerView.adapter = mAdapter

        folderWindow = FolderPopWindow(this)
        folderWindow!!.setArrowImageView(mIvArrow)
        folderWindow!!.setOnAlbumItemClickListener(this)
        mRecyclerView.setOnRecyclerViewPreloadListener(object :
            PreloadRecyclerView.OnRecyclerViewPreloadMoreListener {
            override fun onRecyclerViewPreloadMore() {
                if (hasMore) {
                    loadMoreData()
                }
            }
        })

        mAdapter.setOnPhotoSelectChangedListener(object : OnPhotoSelectChangedListener<LocalMedia> {
            override fun onTakePhoto() {
            }

            override fun onChange(data: MutableList<LocalMedia>) {
                changeImageNumber(data)
            }

            override fun onPictureClick(data: LocalMedia?, position: Int) {
            }

        })

    }

    private fun initPageModel2(folders: List<LocalMediaFolder>) {
        folderWindow.bindFolder(folders)
        mPage = 1
        val folder: LocalMediaFolder = folderWindow.getFolder(0)
        mTvPictureTitle.setTag(R.id.view_count_tag, folder?.imageNum ?: 0)
        mTvPictureTitle.setTag(R.id.view_index_tag, 0)
        val bucketId = folder?.bucketId ?: -1
        mRecyclerView.setEnableLoadMore(true)

        lifecycleScope.launch(Dispatchers.Main) {
            mData.addAll(getMediaData(bucketId))
            mAdapter.notifyDataSetChanged()
        }

    }

    private fun loadMoreData() {
        mPage++
        val bucketId = ValueOf.toLong(mTvPictureTitle.getTag(R.id.view_tag))
        lifecycleScope.launch(Dispatchers.Main) {
            mData.addAll(getMediaData(bucketId))
            mAdapter.notifyDataSetChanged()
        }
    }

    //将耗时任务切到IO线程去执行
    private suspend fun getMediaData(bucketId: Long): List<LocalMedia> =
        withContext(Dispatchers.IO) {
            var list = arrayListOf<LocalMedia>()
            LocalMediaLoader.instance.loadPageMediaData(bucketId, mPage,
                label@ OnQueryDataResultListener { data: List<LocalMedia>, currentPage: Int, isHasMore: Boolean ->
                    if (!isFinishing) {
                        list.addAll(data)

                    }
                })

            return@withContext list
        }

    override fun onItemClick(
        position: Int,
        isCameraFolder: Boolean,
        bucketId: Long,
        folderName: String?,
        data: MutableList<LocalMedia>?
    ) {
        mTvPictureTitle.text = folderName
        val currentBucketId =
            ValueOf.toLong(mTvPictureTitle.getTag(R.id.view_tag))
        mTvPictureTitle.setTag(R.id.view_tag, bucketId)
        if (currentBucketId != bucketId) {
            mPage = 1
            LocalMediaLoader.instance.loadPageMediaData(bucketId, mPage,
                OnQueryDataResultListener { result: List<LocalMedia>, currentPage: Int, isHasMore: Boolean ->
                    if (!isFinishing) {
                        mData.clear()
                        mData.addAll(result)
                        mAdapter.notifyDataSetChanged()
                        mRecyclerView.onScrolled(0, 0)
                        mRecyclerView.smoothScrollToPosition(0)
                        folderWindow.dismiss()
                    }
                })

        }
    }

    override fun onClick(v: View?) {
        val id = v?.id
        if (id == R.id.picture_title || id == R.id.ivArrow || id == R.id.viewClickMask) {
            if (folderWindow.isShowing) {
                folderWindow.dismiss()
            } else {
                if (!folderWindow.isEmpty) {
                    folderWindow.showAsDropDown(mTitleBar)
                }
            }
            return
        }
        if (id == R.id.picture_tv_ok) {
            onCompleted()
        }
    }

    private fun onCompleted() {
        val seletedList = mAdapter.getSelectedData()
        val intent = Intent().putParcelableArrayListExtra(
            PictureConfig.EXTRA_RESULT_SELECTION, seletedList as ArrayList<out Parcelable>
        )
        setResult(RESULT_OK, intent)
        finish()
    }


    fun changeImageNumber(selectData: List<LocalMedia>) {
        val enable = selectData.size > 0
        if (enable) {
            mTvPictureOk.setEnabled(true);
            mTvPictureOk.setSelected(true);
            mTvPicturePreview.setEnabled(true);
            mTvPicturePreview.setSelected(true);
            mTvPicturePreview.text = getString(R.string.picture_preview_num, selectData.size)
            mTvPictureOk.text = getString(R.string.picture_completed)
        } else {
            mTvPictureOk.setEnabled(false);
            mTvPictureOk.setSelected(false);
            mTvPicturePreview.setEnabled(false);
            mTvPicturePreview.setSelected(false);
            mTvPicturePreview.text = getString(R.string.picture_preview)
            mTvPictureOk.text = getString(R.string.picture_please_select)
        }
    }

}